<h1>Manage Theme</h1>
<?php
	if (local_post()) {
		if (authorized('conf', 'update', true)) {
			db_query("UPDATE conf SET value = '{$_POST['theme']}' WHERE name = 'THEME'");
		} else warning('You do not have permission to edit the site conf.');

   	$upload_errors =  array('UPLOAD_ERR_OK', 'UPLOAD_ERR_INI_SIZE', 'UPLOAD_ERR_FORM_SIZE', 'UPLOAD_ERR_PARTIAL', 'UPLOAD_ERR_NO_FILE', 'UPLOAD_ERR_NO_TMP_DIR', 'UPLOAD_ERR_CANT_WRITE', 'UPLOAD_ERR_EXTENSION');
    
    if (!empty($_FILES['upload']['error']) && $_FILES['upload']['error'] != 4) error($upload_errors[$_FILES['upload']['error']]);
		elseif (is_uploaded_file($_FILES['upload']['tmp_name'])) {
  		if (is_writeable(PHPDRIVER . 'themes')) {
  				$cmd = escapeshellcmd(UNZIP_CMD . " {$_FILES['upload']['tmp_name']} -d " . PHPDRIVER . 'themes/');
  				shell_exec("$cmd");
  		} else error('Please chmod 777 ' . PHPDRIVER . ' themes/');
		} else error('Upload failed.');
	}
?>
<form method="post" enctype="multipart/form-data">
	<fieldset>
		<legend>Install a New Theme</legend>
		
		<small>Them Packages consist of a zip file containing exactly one root folder. The name of that folder is the theme name.</small>
		<br />
		
		<label for="upload">
			Select a &quot;theme.zip&quot; file
			<input type="file" name="upload" id="upload" value="" />
		</label>
		
		<input type="submit" value="Upload &amp; Install" />
	</fieldset>

	<fieldset>
		<legend>Current Theme</legend>
		
		<ul>
    <?php
    	foreach (scandir(PHPDRIVER . 'themes/') as $dir) {
    		if (substr($dir, 0, 1) == '.' || $dir == 'admin' || !is_dir(PHPDRIVER . "themes/$dir")) continue;
    		$checked = ($dir == db_result(db_query("SELECT value FROM conf WHERE name = 'THEME'"), 0)) ? 'checked="checked" ' : ''; 
    ?>
			<li>
				<input type="radio" name="theme" value="<?php echo $dir?>"<?php echo $checked?>>
				<?php echo ucwords(str_replace('_', ' ', $dir))?>
			</li>
    <?php	
    	}
    ?>
		</ul>
	</fieldset>
	
	<input type="submit" value="Save" />
</form>